package com.neusoft.bizcore.notice.notification.converter;

import java.util.ArrayList;
import java.util.Arrays;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.neusoft.bizcore.notice.constant.NoticeConsts;
import com.neusoft.bizcore.notice.notification.dto.NoticeRecordSystemDTO;
import com.neusoft.bizcore.notice.notification.model.NoticeRecordSystem;
import com.neusoft.bizcore.notice.notification.model.enums.SendStatus;
import com.neusoft.bizcore.notice.notification.repository.NoticeRecordSystemRepository;
import com.neusoft.bizcore.web.dto.AbstractConverter;

@Component
public class NoticeRecordSystemConverter extends AbstractConverter<NoticeRecordSystem, NoticeRecordSystemDTO> {
    @Autowired
    private NoticeRecordSystemRepository noticeRepository;

    @Override
    public NoticeRecordSystem toModel(final NoticeRecordSystemDTO dto) {
        NoticeRecordSystem model;
        if (dto.isNew()) {
            model = new NoticeRecordSystem();
        } else {
            model = this.noticeRepository.getOne(dto.getId());
        }
        model.setBusinessInfo(dto.getBusinessInfo());
        model.setContent(dto.getContent());
        model.setErrorMsg(dto.getErrorMsg());
        model.setNoticeType(dto.getNoticeType());
        model.setNoticeRoute(dto.getNoticeRoute());
        model.setStatus(SendStatus.valueOf(dto.getStatus().toString()));
        if ((dto.getUsers() != null) && !dto.getUsers().isEmpty()) {
            final StringBuffer users = new StringBuffer();
            dto.getUsers().forEach(t -> {
                users.append(t.trim() + NoticeConsts.SPLIT_COMMA);
            });
            model.setUsers(users.toString());
        }

        return model;
    }

    @Override
    public NoticeRecordSystemDTO toDTO(final NoticeRecordSystem model, final boolean forListView) {

        final NoticeRecordSystemDTO dto = new NoticeRecordSystemDTO();
        dto.setId(model.getId());
        dto.setBusinessInfo(model.getBusinessInfo());
        dto.setContent(model.getContent());
        dto.setErrorMsg(model.getErrorMsg());
        dto.setNoticeType(model.getNoticeType());
        dto.setStatus(model.getStatus().toString());
        dto.setNoticeRoute(model.getNoticeRoute());
        if ((model.getUsers() != null) && !model.getUsers().isEmpty()) {
            dto.setUsers(new ArrayList<>(Arrays.asList(model.getUsers().split(NoticeConsts.SPLIT_COMMA))));
        }
        return dto;
    }
}
